package com.iamteer.day10;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RequestResponse
 */
@WebServlet("/RequestResponse")
public class RequestResponse extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RequestResponse() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		StringBuffer sb = new StringBuffer();
		//HttpServletRequest
		sb.append("--------请求行--------" + "<br/>");
		sb.append("请求方式：" + request.getMethod() + "<br/>");
		sb.append("请求URI：" + request.getRequestURI() + "<br/>");
		sb.append("请求URL：" + request.getRequestURL() + "<br/>");
		sb.append("请求协议：" + request.getProtocol() + "<br/>");
		
		sb.append("--------请求头--------" + "<br/>");
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String headerName = (String) headerNames.nextElement();
			sb.append(headerName + ": " + request.getHeader(headerName) + "<br/>");
		}
		sb.append("referer: " + request.getHeader("referer") + "<br/>");
		
		sb.append("--------参数数据--------" + "<br/>");
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = (String) parameterNames.nextElement();
			sb.append(parameterName + ": " + request.getParameter(parameterName) + "<br/>");
			//如果某些参数有多个，则需要通过 getParameterValues()来获取
			//String[] parameterValues = request.getParameterValues(parameterName);
		}
		
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(sb.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
